from django.db import models
from django.utils.translation import gettext as _

from wagtail.models import Page, Orderable
from wagtail.fields import RichTextField, StreamField
from wagtail.admin.panels import (
    FieldPanel,
    FieldRowPanel,
    InlinePanel,
    MultiFieldPanel,
    PublishingPanel,
)
from wagtail.models import (
    Collection,
    DraftStateMixin,
    Page,
    PreviewableMixin,
    RevisionMixin,
)
from wagtail.search import index
from wagtail.snippets.models import register_snippet

from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField

from .blocks import BaseStreamBlock


@register_snippet
class Person(DraftStateMixin, RevisionMixin, PreviewableMixin, index.Indexed, ClusterableModel,):

    first_name = models.CharField("First name", max_length=254)
    last_name = models.CharField("Last name", max_length=254)
    job_title = models.CharField("Job title", max_length=254)

    image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )

    panels = [
        MultiFieldPanel(
            [
                FieldRowPanel(
                    [
                        FieldPanel("first_name"),
                        FieldPanel("last_name"),
                    ]
                )
            ],
            "Name",
        ),
        FieldPanel("job_title"),
        FieldPanel("image"),
        PublishingPanel(),
    ]

    search_fields = [
        index.SearchField("first_name"),
        index.SearchField("last_name"),
    ]

    @property
    def thumb_image(self):
        # Returns an empty string if there is no profile pic or the rendition
        # file can't be found.
        try:
            return self.image.get_rendition("fill-50x50").img_tag()
        except:  # noqa: E722 FIXME: remove bare 'except:'
            return ""

    @property
    def preview_modes(self):
        return PreviewableMixin.DEFAULT_PREVIEW_MODES + [("blog_post", _("Blog post"))]

    def __str__(self):
        return "{} {}".format(self.first_name, self.last_name)

    def get_preview_template(self, request, mode_name):
        from blog.models import BlogPage

        if mode_name == "blog_post":
            return BlogPage.template
        return "portal/preview/person.html"

    def get_preview_context(self, request, mode_name):
        from blog.models import BlogPage

        context = super().get_preview_context(request, mode_name)
        if mode_name == self.default_preview_mode:
            return context

        page = BlogPage.objects.filter(blog_person_relationship__person=self).first()
        if page:
            page.authors = [
                self if author.pk == self.pk else author for author in page.authors()
            ]
            if not self.live:
                page.authors.append(self)
        else:
            page = BlogPage.objects.first()
            page.authors = [self]

        context["page"] = page
        return context

    class Meta:
        verbose_name = "人员"
        verbose_name_plural = "人员"


@register_snippet
class FooterText(DraftStateMixin, RevisionMixin, PreviewableMixin, models.Model):
    """
    This provides editable text for the site footer. Again it uses the decorator
    `register_snippet` to allow it to be accessible via the admin. It is made
    accessible on the template via a template tag defined in portal/templatetags/
    navigation_tags.py
    """

    body = RichTextField()

    panels = [
        FieldPanel("body"),
        PublishingPanel(),
    ]

    def __str__(self):
        return "Footer text"

    def get_preview_template(self, request, mode_name):
        return "base.html"

    def get_preview_context(self, request, mode_name):
        return {"footer_text": self.body}

    class Meta:
        verbose_name_plural = "底部文字"


class StandardPage(Page):
    """
    A generic content page. On this demo site we use it for an about page but
    it could be used for any type of page content that only needs a title,
    image, introduction and body field
    """

    introduction = models.TextField(help_text="Text to describe the page", blank=True, verbose_name="文字描述")
    image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
        verbose_name="图片"
    )
    body = StreamField(
        BaseStreamBlock(), verbose_name="正文内容", blank=True, use_json_field=True
    )
    content_panels = Page.content_panels + [
        FieldPanel("introduction"),
        FieldPanel("body"),
        FieldPanel("image"),
    ]


class HomePage(Page):
    # Promo section of the HomePage
    promo_image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text="促销图片",
    )
    promo_title = models.CharField(
        blank=True, max_length=255, help_text="要在促销副本上方显示的标题 "
    )
    promo_text = RichTextField(
        null=True, blank=True, max_length=1000, help_text="写一些宣传文案"
    )

    # Body section of the HomePage
    body = StreamField(
        BaseStreamBlock(),
        verbose_name="主页内容块",
        blank=True,
        use_json_field=True,
    )

    fs_1_title = models.CharField(
        blank=True, max_length=255, help_text="要在促销副本上方显示的标题"
    )

    fs_1 = models.ForeignKey(
        "wagtailcore.Page",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text="主页的第一个特色部分。将显示最多三个子项。",
        verbose_name="特色部分1",
    )

    fs_2_title = models.CharField(
        blank=True, max_length=255, help_text="要在促销副本上方显示的标题"
    )

    fs_2 = models.ForeignKey(
        "wagtailcore.Page",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text="主页的第二个特色部分。将显示最多三个子项。",
        verbose_name="特色部分2",
    )

    fs_3_title = models.CharField(
        blank=True, max_length=255, help_text="要在促销副本上方显示的标题"
    )

    fs_3 = models.ForeignKey(
        "wagtailcore.Page",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text="主页的第三个特色部分。将显示最多六个子项。",
        verbose_name="特色部分3",
    )

    content_panels = Page.content_panels + [
        InlinePanel('home_carousel', label="轮播图"),
        MultiFieldPanel(
            [
                FieldPanel("promo_image"),
                FieldPanel("promo_title"),
                FieldPanel("promo_text"),
            ],
            heading="促销部分",
        ),
        FieldPanel('body'),
        MultiFieldPanel(
            [
                MultiFieldPanel(
                    [
                        FieldPanel("fs_1_title"),
                        FieldPanel("fs_1"),
                    ]
                ),
                MultiFieldPanel(
                    [
                        FieldPanel("fs_2_title"),
                        FieldPanel("fs_2"),
                    ]
                ),
                MultiFieldPanel(
                    [
                        FieldPanel("fs_3_title"),
                        FieldPanel("fs_3"),
                    ]
                ),
            ],
            heading="主页特色部分",
        ),
    ]

    promote_panels = [
        MultiFieldPanel(Page.promote_panels, "自定义页面设置"),
    ]


class GalleryPage(Page):
    """
    This is a page to list locations from the selected Collection. We use a Q
    object to list any Collection created (/admin/collections/) even if they
    contain no items. In this demo we use it for a GalleryPage,
    and is intended to show the extensibility of this aspect of Wagtail
    """

    introduction = models.TextField(help_text="Text to describe the page", blank=True, verbose_name="描述")
    image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        help_text="仅限横向模式；水平宽度介于1000px和3000px之间。",
        verbose_name="图片"
    )
    body = StreamField(
        BaseStreamBlock(), verbose_name="正文内容", blank=True, use_json_field=True
    )
    collection = models.ForeignKey(
        Collection,
        limit_choices_to=~models.Q(name__in=["Root"]),
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        help_text="为这个图集选择图片集合",
        verbose_name="集合",
    )

    content_panels = Page.content_panels + [
        FieldPanel("introduction"),
        FieldPanel("body"),
        FieldPanel("image"),
        FieldPanel("collection"),
    ]

    # Defining what content type can sit under the parent. Since it's a blank
    # array no subpage can be added
    subpage_types = []


class Carousel(Orderable):
    page = ParentalKey(HomePage, related_name="home_carousel", on_delete=models.CASCADE)
    image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    rt_image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    title = models.CharField(
        blank=True, max_length=255, help_text="轮播图标题"
    )
    introduction = models.TextField(help_text="轮播图描述文字", blank=True)
    url = models.ForeignKey(
        "wagtailcore.Page",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name="链接",
        help_text="广告图片要链接的页面",
    )


class FormField(AbstractFormField):
    page = ParentalKey("FormPage", related_name="form_fields", on_delete=models.CASCADE)


class FormPage(AbstractEmailForm):
    image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name="图片"
    )
    body = StreamField(BaseStreamBlock(), use_json_field=True, verbose_name="正文内容")
    thank_you_text = RichTextField(blank=True)

    # Note how we include the FormField object via an InlinePanel using the
    # related_name value
    content_panels = AbstractEmailForm.content_panels + [
        FieldPanel("image"),
        FieldPanel("body"),
        InlinePanel("form_fields", heading="表单", label="Field"),
        FieldPanel("thank_you_text"),
        MultiFieldPanel(
            [
                FieldRowPanel(
                    [
                        FieldPanel("from_address"),
                        FieldPanel("to_address"),
                    ]
                ),
                FieldPanel("subject"),
            ],
            "邮箱设置",
        ),
    ]
